<template>
  <el-card>
    <div class="report-nav">
      <el-radio-group v-model="activeGroup" size="large">
        <el-radio-button v-for="g in groupList" :key="g.key" :value="g.key">{{ g.label }}</el-radio-button>
      </el-radio-group>
      <el-select v-model="activeReport" style="margin-left: 24px; width: 220px;">
        <el-option
          v-for="item in currentGroupReports"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <!-- 删除自定义导出按钮 -->
    </div>
    
    <!-- 员工打包工作量图表 -->
    <div v-if="activeGroup === 'stock'" class="chart-section">
      <el-card class="chart-card">
        <div class="chart-header">
          <h3>员工打包工作量统计</h3>
          <div class="chart-controls">
            <el-date-picker
              v-model="chartDateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleChartDateChange"
              style="width: 250px;"
            />
          </div>
        </div>
        <div ref="workloadChart" class="workload-chart"></div>
      </el-card>
    </div>
    
    <component :is="currentReport.component" v-if="currentReport" :key="activeReport" />
    <!-- 删除自定义导出弹窗 -->
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import * as echarts from 'echarts'
import OrderDetail from './sales/OrderDetail.vue'
import ProductTop from './sales/ProductTop.vue'
import Channel from './sales/Channel.vue'
import MemberDetail from './member/Detail.vue'
import MemberLevel from './member/Level.vue'
import ProductDetail from './product/Detail.vue'
import ProductMove from './product/Move.vue'
import StockWarning from './product/StockWarning.vue'
import PointsGrant from './points/Grant.vue'
import PointsConsume from './points/Consume.vue'
import PointsBalance from './points/Balance.vue'
import StockDetail from './stock/Detail.vue'
import StockChange from './stock/Change.vue'
import StockShipmentChannel from './stock/ShipmentChannel.vue'
import EmployeeShipment from './stock/EmployeeShipment.vue'
import ServiceTicket from './service/Ticket.vue'
import ServiceSession from './service/Session.vue'

const groupList = [
  { key: 'sales', label: '销售报表' },
  { key: 'member', label: '会员报表' },
  { key: 'product', label: '商品报表' },
  { key: 'points', label: '积分报表' },
  { key: 'stock', label: '库存报表' },
  { key: 'service', label: '客服报表' }
]

const reportList = [
  { key: 'order-detail', label: '订单明细报表', group: 'sales', component: OrderDetail },
  { key: 'product-top', label: '商品销售排行', group: 'sales', component: ProductTop },
  { key: 'sales-channel', label: '渠道销售统计', group: 'sales', component: Channel },
  { key: 'member-detail', label: '会员明细报表', group: 'member', component: MemberDetail },
  { key: 'member-level', label: '会员等级分布', group: 'member', component: MemberLevel },
  { key: 'product-detail', label: '商品明细报表', group: 'product', component: ProductDetail },
  { key: 'product-move', label: '商品动销/滞销报表', group: 'product', component: ProductMove },
  { key: 'product-stock-warning', label: '商品库存预警', group: 'product', component: StockWarning },
  { key: 'points-grant', label: '积分发放明细', group: 'points', component: PointsGrant },
  { key: 'points-consume', label: '积分消耗明细', group: 'points', component: PointsConsume },
  { key: 'points-balance', label: '积分余额报表', group: 'points', component: PointsBalance },
  { key: 'stock-detail', label: '库存明细报表', group: 'stock', component: StockDetail },
  { key: 'stock-change', label: '异常情况统计', group: 'stock', component: StockChange },
  { key: 'stock-shipment-channel', label: '发货渠道分析', group: 'stock', component: StockShipmentChannel },
  { key: 'employee-shipment', label: '员工发货统计', group: 'stock', component: EmployeeShipment },
  { key: 'service-ticket', label: '工单明细报表', group: 'service', component: ServiceTicket },
  { key: 'service-session', label: '客服会话明细', group: 'service', component: ServiceSession }
]

const activeGroup = ref(groupList[0].key)
const currentGroupReports = computed(() => reportList.filter(r => r.group === activeGroup.value))
const activeReport = ref(currentGroupReports.value[0].key)
const currentReport = computed(() => reportList.find(r => r.key === activeReport.value))

// 图表相关变量
const chartDateRange = ref(['2024-08-01', '2024-08-14'])
const workloadChart = ref<HTMLElement>()
let chartInstance: echarts.ECharts | null = null

// 员工姓名列表
const packagers = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十']

watch(activeGroup, (val) => {
  const first = reportList.find(r => r.group === val)
  if (first) activeReport.value = first.key
})

// 生成员工打包工作量数据
const generateWorkloadData = (startDate: string, endDate: string) => {
  const start = new Date(startDate)
  const end = new Date(endDate)
  const data: any[] = []
  
  let current = new Date(start)
  while (current <= end) {
    const month = current.getMonth() + 1
    const date = current.getDate()
    
    // 为每个员工生成数据
    packagers.forEach(packager => {
      const japanPostEMS = Math.floor(Math.random() * 50) + 10
      const dhl = Math.floor(Math.random() * 30) + 5
      const airFreight = Math.floor(Math.random() * 40) + 8
      const seaFreight = Math.floor(Math.random() * 25) + 3
      const japanDomestic = Math.floor(Math.random() * 35) + 6
      const direct = Math.floor(Math.random() * 20) + 4
      const directMail = Math.floor(Math.random() * 45) + 12
      
      const total = japanPostEMS + dhl + airFreight + seaFreight + japanDomestic + direct + directMail
      
      data.push({
        date: `${month}月${date}日`,
        packager,
        total
      })
    })
    
    current.setDate(current.getDate() + 1)
  }
  
  return data
}

// 初始化图表
const initChart = () => {
  if (!workloadChart.value) return
  
  chartInstance = echarts.init(workloadChart.value)
  updateChart()
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    chartInstance?.resize()
  })
}

// 更新图表数据
const updateChart = () => {
  if (!chartInstance) return
  
  const data = generateWorkloadData(chartDateRange.value[0], chartDateRange.value[1])
  
  // 按员工汇总数据
  const employeeTotals: { [key: string]: number } = {}
  data.forEach(item => {
    if (!employeeTotals[item.packager]) {
      employeeTotals[item.packager] = 0
    }
    employeeTotals[item.packager] += item.total
  })
  
  const option = {
    title: {
      text: '员工打包工作量统计',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params: any) {
        return `${params[0].name}<br/>${params[0].seriesName}: ${params[0].value}件`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: Object.keys(employeeTotals),
      axisLabel: {
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '打包数量(件)'
    },
    series: [
      {
        name: '打包数量',
        type: 'bar',
        data: Object.values(employeeTotals),
        itemStyle: {
          color: '#409eff'
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c}件'
        }
      }
    ]
  }
  
  chartInstance.setOption(option)
}

// 处理图表日期变化
const handleChartDateChange = () => {
  updateChart()
}

// 组件挂载时初始化图表
onMounted(() => {
  // 延迟初始化，确保DOM已渲染
  setTimeout(() => {
    if (activeGroup.value === 'stock') {
      initChart()
    }
  }, 100)
})

// 监听activeGroup变化，当切换到库存报表时初始化图表
watch(activeGroup, (val) => {
  if (val === 'stock') {
    setTimeout(() => {
      initChart()
    }, 100)
  }
})

// 组件卸载时清理图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', () => {
    chartInstance?.resize()
  })
})
</script>

<style scoped>
.report-nav {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 16px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  color: #303133;
}

.chart-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.workload-chart {
  height: 400px;
  width: 100%;
}

.export-field-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.export-field-row .el-checkbox {
  flex: 1;
}
</style> 